import 'package:flutter/material.dart';
import '../models/course.dart';
import '../services/course_service.dart';
import '../utils/theme_colors.dart';

class CourseDetailScreen extends StatefulWidget {
  final String courseId;

  const CourseDetailScreen({
    Key? key,
    required this.courseId,
  }) : super(key: key);

  @override
  State<CourseDetailScreen> createState() => _CourseDetailScreenState();
}

class _CourseDetailScreenState extends State<CourseDetailScreen>
    with TickerProviderStateMixin {
  final CourseService _courseService = CourseService.instance;
  Course? _course;
  bool _isLoading = true;
  bool _isFavorited = false;
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    _loadCourseDetail();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadCourseDetail() async {
    try {
      final course = await _courseService.getCourseById(widget.courseId);
      if (mounted) {
        setState(() {
          _course = course;
          _isFavorited = course?.isFavorited ?? false;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载课程详情失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        body: const Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    if (_course == null) {
      return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        body: const Center(
          child: Text('课程不存在'),
        ),
      );
    }

    return Scaffold(
      body: CustomScrollView(
        slivers: [
          _buildSliverAppBar(),
          SliverToBoxAdapter(
            child: Column(
              children: [
                _buildBasicInfo(),
                _buildTabSection(),
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: _buildBottomBar(),
    );
  }

  Widget _buildSliverAppBar() {
    return SliverAppBar(
      expandedHeight: 200,
      pinned: true,
      backgroundColor: ThemeColors.primary,
      flexibleSpace: FlexibleSpaceBar(
        background: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                ThemeColors.primary,
                ThemeColors.secondary,
              ],
            ),
          ),
          child: Stack(
            children: [
              Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.play_circle_outline,
                      size: 60,
                      color: Colors.white.withOpacity(0.8),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '课程预览',
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.8),
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
              // 状态标签
              Positioned(
                top: 100,
                left: 16,
                child: _buildStatusBadge(),
              ),
            ],
          ),
        ),
      ),
      actions: [
        IconButton(
          onPressed: _toggleFavorite,
          icon: Icon(
            _isFavorited ? Icons.favorite : Icons.favorite_border,
            color: _isFavorited ? Colors.red : Colors.white,
          ),
        ),
        IconButton(
          onPressed: _shareCourse,
          icon: const Icon(Icons.share, color: Colors.white),
        ),
      ],
    );
  }

  Widget _buildStatusBadge() {
    Color backgroundColor;
    String text;
    
    switch (_course!.status) {
      case CourseStatus.upcoming:
        backgroundColor = Colors.orange;
        text = '即将开课';
        break;
      case CourseStatus.enrolling:
        backgroundColor = Colors.blue;
        text = '报名中';
        break;
      case CourseStatus.ongoing:
        backgroundColor = Colors.green;
        text = '正在进行';
        break;
      case CourseStatus.completed:
        backgroundColor = Colors.grey;
        text = '已结束';
        break;
      case CourseStatus.cancelled:
        backgroundColor = Colors.red;
        text = '已取消';
        break;
    }
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(15),
      ),
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _buildBasicInfo() {
    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 课程标题
          Text(
            _course!.title,
            style: const TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          
          // 课程描述
          Text(
            _course!.description,
            style: TextStyle(
              fontSize: 14,
              color: ThemeColors.textSecondary,
              height: 1.5,
            ),
          ),
          const SizedBox(height: 16),
          
          // 讲师信息
          Row(
            children: [
              CircleAvatar(
                radius: 20,
                backgroundColor: ThemeColors.primary.withOpacity(0.1),
                child: Text(
                  _course!.instructor.name.substring(0, 1),
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: ThemeColors.primary,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _course!.instructor.name,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    Text(
                      _course!.instructor.title,
                      style: TextStyle(
                        fontSize: 12,
                        color: ThemeColors.textSecondary,
                      ),
                    ),
                  ],
                ),
              ),
              // 评分
              Row(
                children: [
                  Icon(
                    Icons.star,
                    size: 16,
                    color: Colors.amber,
                  ),
                  const SizedBox(width: 4),
                  Text(
                    _course!.instructor.rating.toString(),
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 16),
          
          // 课程统计
          Row(
            children: [
              _buildStatItem(Icons.people, '${_course!.enrolledCount}', '学员'),
              const SizedBox(width: 24),
              _buildStatItem(Icons.access_time, '${_course!.duration}', '小时'),
              const SizedBox(width: 24),
              _buildStatItem(Icons.video_library, '${_course!.chapters.length}', '章节'),
              const Spacer(),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: ThemeColors.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  _course!.type.displayName,
                  style: TextStyle(
                    fontSize: 12,
                    color: ThemeColors.primary,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(IconData icon, String value, String label) {
    return Column(
      children: [
        Icon(
          icon,
          size: 20,
          color: ThemeColors.primary,
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: ThemeColors.textSecondary,
          ),
        ),
      ],
    );
  }

  Widget _buildTabSection() {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          TabBar(
            controller: _tabController,
            labelColor: ThemeColors.primary,
            unselectedLabelColor: ThemeColors.textSecondary,
            indicatorColor: ThemeColors.primary,
            tabs: const [
              Tab(text: '课程大纲'),
              Tab(text: '学员评价'),
              Tab(text: '相关推荐'),
              Tab(text: '学习社区'),
            ],
          ),
          SizedBox(
            height: 400,
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildCurriculumTab(),
                _buildReviewsTab(),
                _buildRecommendationsTab(),
                _buildCommunityTab(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCurriculumTab() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _course!.chapters.length,
      itemBuilder: (context, index) {
        final chapter = _course!.chapters[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          child: ExpansionTile(
            title: Text(
              chapter.title,
              style: const TextStyle(
                fontWeight: FontWeight.w600,
              ),
            ),
            subtitle: Text(
              '${chapter.lessons.length}节课 · ${chapter.duration}分钟',
              style: TextStyle(
                color: ThemeColors.textSecondary,
                fontSize: 12,
              ),
            ),
            children: chapter.lessons.map((lesson) {
              return ListTile(
                leading: Icon(
                  lesson.isCompleted ? Icons.check_circle : Icons.play_circle_outline,
                  color: lesson.isCompleted ? Colors.green : ThemeColors.primary,
                  size: 20,
                ),
                title: Text(
                  lesson.title,
                  style: const TextStyle(fontSize: 14),
                ),
                subtitle: Text(
                  '${lesson.duration}分钟',
                  style: TextStyle(
                    color: ThemeColors.textSecondary,
                    fontSize: 12,
                  ),
                ),
                trailing: lesson.isFree
                    ? const Text(
                        '免费',
                        style: TextStyle(
                          color: Colors.green,
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                        ),
                      )
                    : null,
                onTap: () {
                  // 播放课程
                },
              );
            }).toList(),
          ),
        );
      },
    );
  }

  Widget _buildReviewsTab() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: 5, // 模拟评价数据
      itemBuilder: (context, index) {
        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    CircleAvatar(
                      radius: 16,
                      backgroundColor: ThemeColors.primary.withOpacity(0.1),
                      child: Text(
                        '用',
                        style: TextStyle(
                          fontSize: 12,
                          color: ThemeColors.primary,
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '用户${index + 1}',
                      style: const TextStyle(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const Spacer(),
                    Row(
                      children: List.generate(5, (starIndex) {
                        return Icon(
                          Icons.star,
                          size: 14,
                          color: starIndex < 4 ? Colors.amber : Colors.grey[300],
                        );
                      }),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  '课程内容很丰富，老师讲解得很详细，学到了很多实用的技能。推荐给大家！',
                  style: TextStyle(
                    fontSize: 14,
                    color: ThemeColors.textSecondary,
                    height: 1.4,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  '2024-01-${15 + index}',
                  style: TextStyle(
                    fontSize: 12,
                    color: ThemeColors.textSecondary,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildRecommendationsTab() {
    return FutureBuilder<List<Course>>(
      future: _courseService.getRecommendedCourses(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
        
        final courses = snapshot.data ?? [];
        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: courses.length,
          itemBuilder: (context, index) {
            final course = courses[index];
            return Card(
              margin: const EdgeInsets.only(bottom: 12),
              child: ListTile(
                leading: Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    gradient: LinearGradient(
                      colors: [
                        ThemeColors.primary.withOpacity(0.8),
                        ThemeColors.secondary.withOpacity(0.8),
                      ],
                    ),
                  ),
                  child: const Icon(
                    Icons.play_circle_outline,
                    color: Colors.white,
                  ),
                ),
                title: Text(
                  course.title,
                  style: const TextStyle(
                    fontWeight: FontWeight.w600,
                  ),
                ),
                subtitle: Text(
                  '${course.instructor.name} · ${course.enrolledCount}人学习',
                  style: TextStyle(
                    color: ThemeColors.textSecondary,
                    fontSize: 12,
                  ),
                ),
                trailing: Text(
                  course.price > 0 ? '¥${course.price}' : '免费',
                  style: TextStyle(
                    color: course.price > 0 ? ThemeColors.primary : Colors.green,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => CourseDetailScreen(
                        courseId: course.id,
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildCommunityTab() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.forum_outlined,
            size: 64,
            color: Colors.grey,
          ),
          SizedBox(height: 16),
          Text(
            '学习社区功能开发中...',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Row(
        children: [
          // 价格信息
          Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (_course!.price > 0) ...[
                Text(
                  '¥${_course!.price}',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: ThemeColors.primary,
                  ),
                ),
              ] else ...[
                const Text(
                  '免费',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.green,
                  ),
                ),
              ],
            ],
          ),
          const SizedBox(width: 16),
          
          // 操作按钮
          Expanded(
            child: _course!.isEnrolled
                ? ElevatedButton(
                    onPressed: _continueLearning,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ThemeColors.primary,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                    child: const Text(
                      '继续学习',
                      style: TextStyle(color: Colors.white),
                    ),
                  )
                : ElevatedButton(
                    onPressed: _enrollCourse,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ThemeColors.primary,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                    child: const Text(
                      '立即报名',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
          ),
        ],
      ),
    );
  }

  Future<void> _toggleFavorite() async {
    try {
      if (_isFavorited) {
        await _courseService.unfavoriteCourse(widget.courseId, 'current_user');
      } else {
        await _courseService.favoriteCourse(widget.courseId, 'current_user');
      }
      setState(() {
        _isFavorited = !_isFavorited;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(_isFavorited ? '已添加到收藏' : '已取消收藏'),
        ),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: $e')),
      );
    }
  }

  void _shareCourse() {
    // 实现分享功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('分享功能开发中...')),
    );
  }

  Future<void> _enrollCourse() async {
    try {
      await _courseService.enrollCourse(widget.courseId, 'current_user');
      // 重新加载课程数据以获取最新状态
      await _loadCourseDetail();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('报名成功！')),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('报名失败: $e')),
      );
    }
  }

  void _continueLearning() {
    // 跳转到学习页面
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('跳转到学习页面...')),
    );
  }
}